import sys
import codecs
import warnings
import pymongo
import pymysql

sys.stdout = codecs.getwriter('utf-8')(sys.stdout.detach())
warnings.filterwarnings("ignore")


class SjName:
    def __init__(self):

        # 连接MongoDB
        self.myclient = pymongo.MongoClient("mongodb://localhost:27017/")
        mydb = self.myclient["xp_analyse"]
        self.my_product = mydb["wt_order_product"]
        self.my_task = mydb["wt_task"]
        self.config = []

        # 连接MySQL
        self.conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='1c7fbf0cc97c57df', db='ceping_system', use_unicode=True, charset="utf8")

    # 更新产品表中产品的数据名，没有数据名则取产品名
    def update_sj_name(self):
        month = sys.argv[1]
        match = {'month': month, "sj_name": {"$exists": False}}
        products = self.my_product.find(match, no_cursor_timeout=True)

        # 更新该月更新数据名状态为抓取中
        self.my_task.update_one({"month": month}, {"$set": {"update_sj_name_extra_completed": 'pending'}})

        for product in products:
            with self.conn.cursor() as cursor:
                sql = "select group_concat(distinct up.product_name) as product_names, up.asin, group_concat(distinct sa.sj_change_name) as sj_change_names from core_unique_sku_product up LEFT JOIN core_amazon_small_apply sa ON up.product_name = RTRIM(LTRIM(sa.cg_change_name)) where up.asin = '" + str(product['asin']) + "'"
                cursor.execute(sql)
                item = cursor.fetchone()

                if item[0] is not None:
                    if item[2] is not None:
                        sj_name = item[2].split(',')[0]
                        print('asin：' + product['asin'] + ' 更新数据名 ' + sj_name)
                    else:
                        sj_name = item[0].split(',')[0]
                        print(product['asin'] + ' 无数据名，已使用产品名《' + sj_name + '》')
                    re = self.my_product.update_many({'month': month, 'asin': product['asin']}, {"$set": {"sj_name": sj_name}})
                    print(re.modified_count)
                else:
                    print(product['asin'] + ' 未找到数据名')

        # 更新该月更新数据名状态为已完成
        self.my_task.update_one({"month": month}, {"$set": {"update_sj_name_extra_completed": 'completed'}})
        products.close()
        self.myclient.close()
        exit()


sj_name = SjName()
sj_name.update_sj_name()
